<?php
try {
	/*
	 * 自动获取天气存入数据库
     */
	@header ( 'Content-type:text/html;charset=UTF-8' );

	define ( 'MacTop', true );
	define ( 'Root', dirname ( __FILE__ ) );
	
	require_once Root . '/common.inc.php';
	require_once Root . '/function.inc.php';
	GetCentralConnection ();

	$sql="select cityid,cityname from weather_city ";
	$result = mysql_query ( $sql, $centraldb );
	if(!$result)
		throw new Exception ( 'no data' );
	
	$nowtime=time();
	
	//更新天气信息
	while ( $row_t = mysql_fetch_array ( $result ) ) {
				$url = 'http://www.weather.com.cn/data/cityinfo/'.$row_t['cityid'].'.html';//查询天气
	    		$weather = json_decode(file_get_contents($url));
	    		if(!$weather)
					continue;
					
				if(strtotime(date('Y-m-d '.$weather->weatherinfo->ptime))> $nowtime){
					break;
				}
				
				$sql='insert ignore weather (cityid,temp1,temp2,weather,img1,img2,ptime,day,addtime) values ("'.$row_t['cityid'].'","'.$weather->weatherinfo->temp1.'","'.$weather->weatherinfo->temp2.'","'.$weather->weatherinfo->weather.'","'.$weather->weatherinfo->img1.'","'.$weather->weatherinfo->img2.'","'.$weather->weatherinfo->ptime.'","'.date('Ymd',$nowtime).'","'.$nowtime.'")';
				mysql_query ( $sql, $centraldb );
	}
	
	
				
				$pmurl='http://pm25.in/api/querys/pm2_5.json?city='.$row_t['cityname'].'&token=5j1znBVAsnSf5xQyNQyq&stations=no';//查询空气质量
				$pm25=json_decode(file_get_contents($pmurl));
				if(empty($pm25->error)){
					if($pm25){
						$sql='insert ignore weather (cityid,temp1,temp2,weather,img1,img2,ptime,day,addtime,pm2_5,quality) values ("'.$row_t['cityid'].'","'.$weather->weatherinfo->temp1.'","'.$weather->weatherinfo->temp2.'","'.$weather->weatherinfo->weather.'","'.$weather->weatherinfo->img1.'","'.$weather->weatherinfo->img2.'","'.$weather->weatherinfo->ptime.'","'.date('Ymd',$nowtime).'","'.$nowtime.'","'.$pm25[0]->pm2_5.'","'.$pm25[0]->quality.'")';
					}
				}
				
				//echo $sql;exit;
				mysql_query ( $sql, $db );
	}
	
	
	$nowdate=date('Ymd');
    $results = mysql_query ( "select *  from weather_v where day=".$nowdate." and (quality='' or quality=null) order by addtime desc", $db );
	while ( $row_ts = mysql_fetch_array ( $results ) ) {
		if($row_ts['quality']=="" || $row_ts['quality']==null){
			$pmurl='http://pm25.in/api/querys/pm2_5.json?city='.$row_ts['cityname'].'&token=5j1znBVAsnSf5xQyNQyq&stations=no';//查询空气质量
			$pm25=json_decode(file_get_contents($pmurl));
			$sql1='update weather set quality="'.$pm25[0]->quality.'", pm2_5="'.$pm25[0]->pm2_5.'" where weatherid='.$row_ts['weatherid'].'';
			
			mysql_query ( $sql1, $db );
		}
	}
	CleanUpCentralDB ();
	exit ();
} catch ( Exception $e ) {
	echo $e->getMessage ();
	exit ();
}
?>